package cn.doitedu.other;

import java.util.ArrayList;
import java.util.List;

public class BinSearcher {

    public static <T> int binSearch(List<? extends Comparable<T>> lst,T t){
        int start = 0;
        int end = lst.size()-1;
        int mid ;

        while(start<=end){
            mid = (end-start)/2 + start;
            if(lst.get(mid).compareTo(t) >0){
                end = mid-1;
            }else  if(lst.get(mid).compareTo(t)<0){
                start = mid+1;
            }else{
                return mid;
            }
        }
        return -1;
    }

    public static void main(String[] args) {
        ArrayList<Integer> lst = new ArrayList<>();
        lst.add(5);
        lst.add(8);
        lst.add(15);
        lst.add(20);
        lst.add(25);

        int i = binSearch(lst, 15);
        System.out.println(i);


        IpBean ip1 = new IpBean(1, 5, "sx1", "cz");
        IpBean ip2 = new IpBean(8, 15, "sx2", "cz");
        IpBean ip3 = new IpBean(16, 25, "sx3", "cz");
        IpBean ip4 = new IpBean(30, 35, "sx4", "cz");
        ArrayList<IpBean> ips = new ArrayList<>();
        ips.add(ip1);
        ips.add(ip2);
        ips.add(ip3);
        ips.add(ip4);

        IpBean ipBean = new IpBean(26, 26, null, null);
        int i1 = binSearch(ips, ipBean);
        if(i1>-1) {
            System.out.println(ips.get(i1));
        }else{
            System.out.println(i1);
        }

    }
}
